<?php
/**
 *
 * 作    者：安德玛
 * 版本控制：	
			20210209------新增任务审核页面优化
			20210210------新增任务审核加用户昵称字段
 * 功能说明：网红任务控制器。
 *
 **/
namespace Admin\Controller;

class UsertaskController extends ComController
{
    /**
     * 接单列表
     */
    public function index()
    {
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $keyword = I('keyword','','htmlspecialchars');
        $status = I('status','','htmlspecialchars');
        $field = I('get.field','','htmlspecialchars');
        $sort = I('get.sort','','htmlspecialchars');
        $model = M();
        $sqlWhere = "1=1 and ";
        
        if($keyword){
            $sqlWhere .= "(b.`title` like '%{$keyword}%' or c.username like '%{$keyword}%' or b.task_no like '%{$keyword}%') and ";
        }
        if($status != ''){
            $this->assign('status',$status);
            if($status == -1){
                $status = 0;
            }
            $sqlWhere .= "a.`status`=".$status." and ";
        }
        $sqlWhere = msubstr($sqlWhere, 0, utf8_strlen($sqlWhere) - 4, "utf-8", false);
        
        $sortSql = "a.id desc";
        if($field and $sort){
            $sortSql = "b.".$field." ".$sort;
        }
        
        $pagesize = 20;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $model->query("select count(*) as total from ".C('DB_PREFIX')."user_task a left join ".C('DB_PREFIX')."task b on a.task_id=b.id left join ".C('DB_PREFIX')."user c on a.uid=c.id where ".$sqlWhere);
        $count = $count[0]['total'];
        $sql = "select a.*,b.`title`,b.task_no,b.cid,b.end_t,b.url,b.pay_status,b.user_level,b.money_type,b.uid as user_id,c.username from ".C('DB_PREFIX')."user_task a left join ".C('DB_PREFIX')."task b on a.task_id=b.id left join ".C('DB_PREFIX')."user c on a.uid=c.id where ".$sqlWhere." order by ".$sortSql." limit ".$offset . "," . $pagesize;
        $list = $model->query($sql);
        foreach ($list as $k=>&$v){
            // 获取平台名称及icon
            $category = M('category')->where(array('id'=>$v['cid']))->find();
            $list[$k]['icon'] = C('URL').$category['icon'];
            $list[$k]['cate_name'] = $category['title'];
            // 获取任务满足条件会员等级
            $user_level = $v['user_level'];
            $user_level_arr = explode(',', $user_level);
            $info_title = '';
            foreach ($user_level_arr as $n=>&$m){
                $info = M('user_level')->where(array('id'=>$m))->field('title')->find();
                $info_title .= $info['title']." ";
            }
            $list[$k]['level_info'] = $info_title;
            
            // 任务要求
            $money_type = $v['money_type'];
            $money_type_arr = explode(',', $money_type);
            $money_info_title = '';
            foreach ($money_type_arr as $h=>&$l){
                $money_info = M('money_type')->where(array('id'=>$l))->field('title')->find();
                $money_info_title .= $money_info['title'].' ';
            }
            $list[$k]['money_info'] = $money_info_title;
			//接单用户昵称
			$id = $v['username'];
			$user_info = M('user')->where('username='.$id)->field('nickname')->find();
			$list[$k]['nickname'] =$user_info['nickname'];
			// $list[$k]['nickname'] =$id;
            
            // 发布人
            if($v['user_id'] == 0){
                $list[$k]['author'] = '平台';
            }else{
                $user = M('user')->where(array('id'=>$v['user_id']))->find();
                $list[$k]['author'] = $user['nickname'];
            }
        }
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('p', $p);
        $this->assign('field',$field);
        $this->assign('sort',$sort);
        $this->display();
    }
    
    
    /**
     * 审核
     */
    public function update()
    {
        $p = I('p',1);
        $status = I('sh_status','');
        $id = I('id','','htmlspecialchars');
        if(!$id){
            $this->error('传参为空');
        }
        if(IS_POST){
            $data['status'] = I('post.status','','htmlspecialchars');
            $data['sh_remark'] = I('post.sh_remark','','htmlspecialchars');
            $data['sh_t'] = time();
            $res = M('user_task')->where(array('id'=>$id))->data($data)->save();
            if($res){
                addlog('接单任务审核，ID：'.$id);
                // 统计任务分佣相关数据
                if($data['status'] == 2){
                    $this->getTaskReward($id);
                    //判断任务是否已完成
                    $this->checkFinishTask($id);
                }else{
                    //审核拒绝需要将任务归还任务池
                    $this->updateTaskPoll($id);
                }
                $this->success('操作成功');
				redirect(U('updateShenhe',array('uid'=>$id,'close'=>1)));
				 die(0);
            }else{
                $this->error('操作失败！');
            }
        }else{
            $sql = "select a.*,b.`title`,b.cid,b.end_t,b.url,b.pay_status,b.user_level,b.money_type,b.uid as user_id,c.username from ".C('DB_PREFIX')."user_task a left join ".C('DB_PREFIX')."task b on a.task_id=b.id left join ".C('DB_PREFIX')."user c on a.uid=c.id where a.id=".$id;
            $model = M();
            $query = $model->query($sql);
            $vo = $query[0];
            if($vo['pics'] != ''){
                $pics = explode(',', $vo['pics']);
                $this->assign('pics',$pics);
            }
            // 获取平台名称及icon
            $category = M('category')->where('id='.$vo['cid'])->find();
            $vo['icon'] = C('URL').$category['icon'];
            $vo['cate_name'] = $category['title'];
            // 获取任务满足条件会员等级
            $user_level = $vo['user_level'];
            $user_level_arr = explode(',', $user_level);
            $where1['id'] = array('in',$user_level_arr);
            $info = M('user_level')->where($where1)->field('title')->select();
            foreach ($info as $val) {
                $val = join(",",$val);
                $temp_array[] = $val;
            }
            $vo['level_info'] = implode(",", $temp_array);
            // 任务要求
            $money_type = $vo['money_type'];
            $money_type_arr = explode(',', $money_type);
            $where2['id'] = array('in',$money_type_arr);
            $money_info = M('money_type')->where($where2)->field('title')->select();
            foreach ($money_info as $val) {
                $val = join(",",$val);
                $temp_array1[] = $val;
            }
            $vo['money_info'] = implode(",", $temp_array1);
            // 发布人
            if($vo['user_id'] == 0){
                $vo['author'] = '平台';
            }else{
                $user = M('user')->where('id='.$vo['user_id'])->find();
                $vo['author'] = $user['nickname'];
            }
            $this->assign('vo',$vo);
            $this->assign('p',$p); 
            $this->assign('sh_status',$status); 
            $this->display('form');
        }
    }
    
    /**
     * 统计任务相关分成数据
     */
    private function getTaskReward($id=0)
    {
        $user_task_info = M('user_task')->where('id='.$id)->find();
        $task = M('task')->where('id='.$user_task_info['task_id'])->find();
        $uid = $user_task_info['uid'];
        $price = floatval($user_task_info['price']);
        // 当前用户更新收益及收益记录
        M('user')->where('id='.$uid)->setInc('money',$price);
        $income_data = array(
            'money'=>$price,
            'type'=>1,
            't'=>time(),
            'remark'=>'完成任务'.$task['title'].',收益'.$price.'元',
            'uid'=>$uid
        );
        M('user_income')->data($income_data)->add();
        // 加入会员动态（任务收益）
        $user = M('user')->where('id='.$uid)->find();
        M('user_dynamic')->data(array('mobile'=>$user['username'],'content'=>'成功获得任务收益','t'=>time()))->add();
        // 加入消息通知
        M('user_message')->data(array('uid'=>$uid,'content'=>'完成'.$task['title'].'任务，获得收益'.$price.'元','t'=>time(),'type'=>2))->add();
        // 计算一级分佣
        $first_pid_info = M('user')->where('id='.$uid)->field('pid')->find();
        if($first_pid_info){
            $first_user_info = M('user')->where('id='.$first_pid_info['pid'])->find();
            if($first_user_info['status'] == 1 && strtotime($first_user_info['expri_day']) > time()){
                // 计算一级推介用户的用户等级及一级任务分佣比列
                $first_user_level_info = M('user_level')->where('id='.$first_user_info['level_id'])->field('fenyong_1')->find();
                $percent = intval($first_user_level_info['fenyong_1']);
                if($percent > 0){
                    // 插入分佣奖励记录
                    $fy_price = round($price * $percent / 100,2);
                    //更新余额
                    M('user')->where('id='.$first_user_info['id'])->setInc('money',$fy_price);
                    //插入收益记录
                    $income_data_1 = array(
                        'money'=>$fy_price,
                        'type'=>2,
                        't'=>time(),
                        'remark'=>'一级任务分佣奖励'.$fy_price.'元',
                        'uid'=>$first_user_info['id']
                    );
                    M('user_income')->data($income_data_1)->add();
                    // 加入会员动态（一级任务分佣奖励）
                    M('user_dynamic')->data(array('mobile'=>$first_user_info['username'],'content'=>'成功获得一级任务分佣奖励','t'=>time()))->add();
                    // 加入消息通知
                    M('user_message')->data(array('uid'=>$first_user_info['id'],'content'=>'一级任务分佣奖励'.$fy_price.'元','t'=>time(),'type'=>2))->add();
                } 
            } 
            // 二级分佣奖励逻辑
            if($first_user_info['pid']){
                $second_user_info = M('user')->where('id='.$first_user_info['pid'])->find();
                if($second_user_info['status'] == 1 && strtotime($second_user_info['expri_day']) > time()){
                    // 计算二级推介用户的用户等级及二级分佣比列
                    $second_user_level_info = M('user_level')->where('id='.$second_user_info['level_id'])->field('fenyong_2')->find();
                    $percent = intval($second_user_level_info['fenyong_2']);
                    if($percent > 0){
                        // 插入分佣记录
                        $fy_price = round($price * $percent / 100,2);
                        //更新余额
                        M('user')->where('id='.$second_user_info['id'])->setInc('money',$fy_price);
                        //插入收益记录
                        $income_data = array(
                            'money'=>$fy_price,
                            'type'=>3,
                            't'=>time(),
                            'remark'=>'二级任务分佣奖励'.$fy_price.'元',
                            'uid'=>$second_user_info['id']
                        );
                        M('user_income')->data($income_data)->add();
                        // 加入会员动态（二级任务分佣奖励）
                        M('user_dynamic')->data(array('mobile'=>$second_user_info['username'],'content'=>'成功获得二级任务分佣奖励','t'=>time()))->add();
                        // 加入消息通知
                        M('user_message')->data(array('uid'=>$second_user_info['id'],'content'=>'二级任务分佣奖励'.$fy_price.'元','t'=>time(),'type'=>2))->add();
                    }
                }
            }
        } 
    }
    
    /**
     * 归还任务池
     * @param number $id
     */
    private function updateTaskPoll($id=0)
    {
        if($id){
            $user_task = M('user_task')->where('id='.$id)->field('task_id,uid')->find();
            $task = M('task')->where('id='.$user_task['task_id'])->field('title')->find();
            // 对应任务已完成数量-1
            M('task')->where('id='.$user_task['task_id'])->setDec('hasdid_num',1);
            // 加入消息通知
            M('user_message')->data(array('uid'=>$user_task['uid'],'content'=>'接单任务'.$task['title'].'审核不通过','t'=>time(),'type'=>2))->add();
        } 
    }
    
    /**
     * 判断任务是否已完成
     * @param number $id
     */
    private function checkFinishTask($id=0)
    {
        if($id){
            $user_task = M('user_task')->where('id='.$id)->field('task_id,uid')->find();
            $task = M('task')->where('id='.$user_task['task_id'])->field('num,title')->find();
            //加入消息通知
            M('user_message')->data(array('uid'=>$user_task['uid'],'content'=>'网红任务'.$task['title'].'已成功完成','t'=>time(),'type'=>2))->add();
        }
    }
    
    /**
     * 删除
     */
    public function delete()
    {
        $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        if ($ids) {
            if (is_array($ids)) {
                $ids = implode(',', $ids);
                $map['id'] = array('in', $ids);
            } else {
                $map = 'id=' . $ids;
            }
            if (M('user_task')->where($map)->delete()) {
                addlog('删除接单详情，ID：' . $ids);
                $this->success('恭喜，删除接单任务！',U('index',array('p'=>$p)));
            } else {
                $this->error('参数错误！');
            }
        } else {
            $this->error('参数错误！');
        }
    }
	/**
	     * 任务审核备注
	     */
	    public function updateShenhe()
	    {
        $p = I('p',1);
        $status = I('sh_status','');
        $id = I('uid','','htmlspecialchars');
        if(!$id){
            $this->error('安德玛是永远的神啊啊啊啊啊啊啊');
        }
        if(IS_POST){
            $data['status'] = I('post.status','','htmlspecialchars');
            $data['sh_remark'] = I('post.sh_remark','','htmlspecialchars');
            $data['sh_t'] = time();
            $res = M('user_task')->where(array('id'=>$id))->data($data)->save();
            if($res){
                addlog('接单任务审核，ID：'.$id);
                // 统计任务分佣相关数据
                if($data['status'] == 2){
                    $this->getTaskReward($id);
                    //判断任务是否已完成
                    $this->checkFinishTask($id);
                }else{
                    //审核拒绝需要将任务归还任务池
                    $this->updateTaskPoll($id);
                }
            }else{
                $this->error('操作失败！');
            }
        }else{
            $sql = "select a.*,b.`title`,b.cid,b.end_t,b.url,b.pay_status,b.user_level,b.money_type,b.uid as user_id,c.username from ".C('DB_PREFIX')."user_task a left join ".C('DB_PREFIX')."task b on a.task_id=b.id left join ".C('DB_PREFIX')."user c on a.uid=c.id where a.id=".$id;
            $model = M();
            $query = $model->query($sql);
            $vo = $query[0];
            if($vo['pics'] != ''){
                $pics = explode(',', $vo['pics']);
                $this->assign('pics',$pics);
            }
            // 获取平台名称及icon
            $category = M('category')->where('id='.$vo['cid'])->find();
            $vo['icon'] = C('URL').$category['icon'];
            $vo['cate_name'] = $category['title'];
            // 获取任务满足条件会员等级
            $user_level = $vo['user_level'];
            $user_level_arr = explode(',', $user_level);
            $where1['id'] = array('in',$user_level_arr);
            $info = M('user_level')->where($where1)->field('title')->select();
            foreach ($info as $val) {
                $val = join(",",$val);
                $temp_array[] = $val;
            }
            $vo['level_info'] = implode(",", $temp_array);
            // 任务要求
            $money_type = $vo['money_type'];
            $money_type_arr = explode(',', $money_type);
            $where2['id'] = array('in',$money_type_arr);
            $money_info = M('money_type')->where($where2)->field('title')->select();
            foreach ($money_info as $val) {
                $val = join(",",$val);
                $temp_array1[] = $val;
            }
            $vo['money_info'] = implode(",", $temp_array1);
            // 发布人
            if($vo['user_id'] == 0){
                $vo['author'] = '平台';
            }else{
                $user = M('user')->where('id='.$vo['user_id'])->find();
                $vo['author'] = $user['nickname'];
            }
            $this->assign('vo',$vo);
            $this->assign('p',$p); 
            $this->assign('sh_status',$status); 
            $this->display('form1');
        }
    }
}